package leecode

import (
	"strconv"
	"strings"
)

func monotoneIncreasingDigits(n int) int {
	if n == 0 {
		return 0
	}
	if n <= 10 {
		return 9
	}
	//将 n 转化为 字符串类型
	nStr := strconv.Itoa(n)
	arr := strings.Split(nStr, "")
	length := len(arr)
	//从后向前遍历
	for i := len(arr) - 1; i-1 >= 0; i-- {
		if arr[i] < arr[i-1] {
			floor, _ := strconv.Atoi(arr[i-1])
			arr[i-1] = strconv.Itoa(floor - 1)
			//后面的全部变为9
			for j := i; j < length; j++ {
				arr[j] = "9"
			}
		}
	}
	resultStr := strings.Join(arr, "")
	result, _ := strconv.Atoi(resultStr)
	return result
}
